import Vue from 'vue'
import Vuex from 'vuex'
import $ from 'jquery'
import router from '@/router';
import ElMessage from 'element-ui';

Vue.use(Vuex)

function rollIndex(idStr) {
  console.log('$(`#${idStr}`)', `${idStr}`)
  console.log('$(`#${idStr}`)', $('[ly-id="ly0"]')[0])
  console.log('$(`#${idStr}`)', $(`[ly-id=${idStr}]`)[0])
  console.log('$(`#${idStr}`)', document.getElementById(`${idStr}`))

  const selectDom = $(`[ly-id=${idStr}]`)[0]
  //
  $(`[ly-id=${idStr}]`).eq(0).parent().css('overflow', 'visible');
  $(`[ly-id=${idStr}]`).eq(0).css('overflow', 'visible');
  $(`[ly-id=${idStr}]`).eq(0).css('border', 'red 2px solid');
  $(`[ly-id=${idStr}]`).eq(0).append("<style>.box::after{content: \"元素需要为正整数 \";color:red;}</style>");
  $(`[ly-id=${idStr}]`).eq(0).css('position', 'relative').after(`<span class="${idStr + '_'}">元素需要为正整数</span>`);
  $(`.${idStr + '_'}`).css({
    'color': 'red',
    'border-radius': '5px',
    'position': 'absolute',
    'bottom': '-30px',
    'left': '20px'
  });


// 设置提示信息渐渐消失的动画效果
  $('.ly0_').animate({
    opacity: 0
  }, 10000, function() {
    // 动画完成后删除元素
    $(this).remove();
  });


// 将新的样式规则添加到页面头部
  document.getElementsByTagName('head')[0].appendChild(css);


  //设置滚动，但是是让html、body滚动
  $("html, body").animate({
    scrollTop: $(`[ly-id=${idStr}]`).eq(0).offset().top
  }, {duration: 500, easing: "swing"});
  $('.el-main').eq(0).animate({
    scrollTop: $(`[ly-id=${idStr}]`).eq(0).offset().top - 40
  }, {duration: 500, easing: "swing"});
  // $('.main').eq(0).animate({
  //   scrollTop: $(`[ly-id=${idStr}]`).eq(0).offset().top
  // }, {duration: 500, easing: "swing"});
}


const state = {
  project: -1,
  basic_data: [],
  goal_reward: [],
  discountData: [],
  rewardList: [],
  type: '',
  //记录自增唯一的埋点id
  uid: 0,
  //校验值 ,{key: _uid, value: { value,type }}
  verifyValue: {},
  //校验事件，暂时保留
  verifyEvent: {},
  //自定义校验，执行返回promise
  verifySelf: {}
}

const getters = {}

const mutations = {
    update: function (state, [name, data]) {
        console.log(name, data)
        let arr = name.split('.')
        console.log('arr', arr)
        let dataNode = state
        let indexKey = ''
        let nowParent;
        console.log('dataNode', dataNode)
        for (let i = 0, len = arr.length; i < len; i++) {
            indexKey = arr[i];
            if (i == 0) {
                nowParent = state
            } else {
                nowParent = nowParent[arr[i - 1]]
            }
            if (nowParent[indexKey] == undefined) {
                nowParent[indexKey] = {}
            }
        }
        nowParent[indexKey] = data
        // console.log('###',state)
        // console.log('nowParent',nowParent)
    },
    verify(state, [path, fun = false, idStr = false]) {
        if (!fun || !idStr) return;
        if (!state.verifyEvent[path]) state.verifyEvent[path] = []
        let eventObj = {
            id: idStr,
            fun: fun
        }
        state.verifyEvent[path].push(eventObj)
        // rollIndex(idStr);
    },
    verifyForm(state, fun) {
        let fullPath = router.history.current.fullPath
        if (state.verifySelf[fullPath]) {

        } else {
            state.verifySelf[fullPath] = []
        }
        state.verifySelf[fullPath].push(fun)
    },
    add(state, n) {
        state.count += n
    },
    reduce(state) {
        state.count--
    }
}

const actions = {
  getVerifyRes(context, fullPath = false, warn = true, roll = true) {
    return new Promise((resolve, reject) => {
      rollIndex('ly0')

      let rollFirst = true
      let signText = false
      if (!fullPath) fullPath = router.history.current.fullPath
      let arr = state.verifyEvent[fullPath]
      if (arr == undefined) arr = []
      let verifiedArr = arr.filter(item => {
        //校验不通过返回 非 false
        // 通过返回false
        let tempSign = item.fun(warn);
        console.log('tempSign', tempSign)
        if (tempSign != false) {
          console.log('校验不通过返回')
          if (!signText) signText = tempSign
          return true
        }
      })
      if (verifiedArr.length && roll && rollFirst) {
        rollFirst = false;
        console.log('11--------------------' + verifiedArr[0].id + '-----');
        alert(`${signText}`)
        rollIndex(verifiedArr[0].id);
      }
      if (verifiedArr && verifiedArr.length == 0) {
        resolve({'state': true, 'allArr': arr, 'referArr': []});
      } else {
        reject({'state': true, 'allArr': arr, 'referArr': verifiedArr})
      }
    })
  },
  getVerifyForm(context, fullPath = false) {
    if (!fullPath) fullPath = router.history.current.fullPath
    let arr = []
    state.verifySelf[fullPath].forEach(funItem => {
      arr.push(funItem());
    })
    return Promise.all(arr)
  }
}

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

